'''
@Project ：my_python_project 
@File    ：模拟tail查看日志案例.py
@IDE     ：PyCharm 
@Author  ：xionglinhui
@Date    ：2024/7/25 上午9:11 
'''
import time
import os


def tail_f(file_path):
    """模拟tail -f命令，实时显示文件最新内容"""
    with open(file_path, 'r') as file:
        # 移动到文件末尾
        file.seek(0, 2)
        while True:
            line = file.readline()
            if not line:
                time.sleep(0.1)  # 如果没有新内容，稍等一会儿再试
                continue
            print(line, end='')  # 打印新内容


def write_log(file_path, message):
    """写入日志，超过100个字符换行"""
    with open(file_path, 'a') as file:
        for i in range(0, len(message), 100):
            file.write(message[i:i + 100] + '\n')


if __name__ == '__main__':
    log_file = 'message.log'

    # 启动一个线程来实时读取日志
    import threading

    threading.Thread(target=tail_f, args=(log_file,)).start()

    # 模拟写入日志
    for i in range(10):
        write_log(log_file, 'a' * 105 + f' This is message {i}')
        time.sleep(1)  # 每隔一秒写入一次